<template>
  <div class="pages_content table mobilebanner">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main>
        <div class="tabtop">
          <div v-for="(item, index) in contractTypelist" :key="index" @click="choose(item.id)">
            <div :class="currenindex == index + 1 ? 'active' : 'text'">{{ item.value }}</div>
          </div>
        </div>
        <div class="header_right" @click="showCardNav = !showCardNav">
          <div class="title">搜索</div>
          <div>
            <div :class="{ 'arrowTransform': !showCardNav, 'arrowTransformReturn': showCardNav}">
              <i style="margin-right: 5px" class="el-icon-arrow-down"></i>
            </div>
          </div>
        </div>
        <div v-show="showCardNav" class="hr"></div>
        <el-collapse-transition>
          <div v-show="showCardNav">
            <div class="search">
              <span style="display: inline-block;margin-bottom: 10px;">
                <span style="margin-right: 12px;">公司</span>
                <el-select v-model="tableParam.companyId" :disabled="UserInfo.adminStatus !== 1" style="width: 240px;" placeholder="请选择">
                  <el-option v-for="(item, index) in companylist" :key="index" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </span>
              <span>
                <span style="margin:0 12px;">状态</span>
                <el-select v-model="tableParam.enable" style="width: 240px;" placeholder="请选择">
                  <el-option label="启用" :value='1'></el-option>
                  <el-option label="禁用" :value='0'></el-option>
                </el-select>
              </span>
              <el-button icon="el-icon-search" size="medium" class="bottom_all but1" @click="(tableParam.page = 1), gettableData()">查 询</el-button>
              <el-button size="medium" class="bottom_all_two" style="margin-left:12px;" @click="init()">重 置</el-button>
            </div>
          </div>
        </el-collapse-transition>
        <div class="hr"></div>
        <div class="card">
          <div class="card_nav">
            <div>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0;" @click="addData()">
                <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
                添加
              </el-button>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='RIYONG'))!==-1" size="small" class="bottom_three" @click="UpdateData(1)">
                <i class="icon iconfont iconicon_button_startuse" style="font-size: 12px;"></i>
                启用
              </el-button>
              <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='JINYONG'))!==-1" size="small" class="bottom_four" @click="UpdateData(0)">
                <i class="icon iconfont iconicon_button_disable1" style="font-size: 12px;"></i>
                禁用
              </el-button>
              <span style="margin:0 20px;">banner底色</span>
              <el-color-picker v-model="bgColor" style="top: 13px;" @change="changeColor"></el-color-picker>
            </div>
          </div>
          <div v-loading="tableLoading" class="card_info" :style="style">
            <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="tableData" tooltip-effect="dark" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55">
              </el-table-column>
              <el-table-column label="序号" type="index" width="50" align="center">
              </el-table-column>
              <el-table-column prop="company" label="公司" width="180" align="center">
              </el-table-column>
              <el-table-column label="图片" width="180" align="center">
                <template slot-scope="scope">
                  <el-image :src="imageUri + scope.row.picturePath"></el-image>
                </template>
              </el-table-column>
              <el-table-column prop="pictureUrl" label="URL" align="center">
              </el-table-column>
              <el-table-column prop="remark" label="备注" align="center">
              </el-table-column>
              <el-table-column prop="enable" label="状态" align="center">
                <template slot-scope="scope">
                  <el-tag>{{scope.row.enable===1?'启用':'禁用'}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column v-if="ButtonList.findIndex(res=>(res.buttonValue=='XIUGAI'))!==-1" label="操作" align="left">
                <template slot-scope="scope">
                  <el-button size="mini" class="bottom_one" @click="handleEdit(scope.row)">
                    修改</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-main>
      <div class="card_bottom">
        <div class="card_bottom_left">
          <div class="top_page_totle">总共{{ total }}条</div>
          <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" layout="prev, pager, next, jumper" :total="total" @current-change="gettableData()"></el-pagination>
        </div>
        <div>
          <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="gettableData">刷新</el-button>
        </div>
      </div>
    </el-container>
    <el-dialog v-dialogDrag :visible.sync="addDialog" width="580px" :close-on-click-modal="false" :before-close="resetFromDate">
      <span slot="title" class="dialog-title">{{ addDialogTitle }}</span>
      <div class="dialoginfo">
        <el-form ref="dialogForm" :inline="true" :model="fromDate" label-width="110px">
          <el-form-item v-if="currenindex===1" prop="companyId">
            <span slot="label" style="color:  #FF0000 ;">公司</span>
            <el-select v-model="fromDate.companyId" :disabled="UserInfo.adminStatus !== 1" placeholder="请选择">
              <el-option v-for="item in companylist" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="picturePath" label-width="110px">
            <span slot="label" style="color:  #FF0000 ;">图片</span>
            <el-upload class="avatar-uploader" action="/resource/resources/upload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="upheader">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item prop="pictureUrl">
            <span slot="label">URL</span>
            <el-input v-model="fromDate.pictureUrl" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item prop="enable">
            <span slot="label">状态</span>
            <el-radio-group v-model="fromDate.enable">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <span slot="label">备注</span>
            <el-input v-model="fromDate.remark" type="textarea" resize="none" style="width:320px" rows="5" placeholder="请输入内容">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetFromDate">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px;" @click="pagessubmitFromDate()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import mixin from "@/mixins/ICPSmixin.js";
import { queryPage, saveOne, updateOne, updateMany, getBgColor, upDataBgColor } from "@/api/basedata/banner.js";
import { getcompany } from "@/api/common.js";
import { getUserInfo } from "@/utils/auth.js";
import { getToken, getUserId } from '@/utils/auth';
export default {
  mixins: [mixin],
  data() {
    return {
      upheader: {
        "access-token": getToken(),
        "user-id": getUserId(),
      },
      UserInfo: '',
      queryPage: queryPage,
      /*表单页类型，0为无树状，1为有树状，有树状在el-main加上display:flex*/
      pagesType: 0,
      /*添加表单数据*/
      contractTypelist: [
        {
          value: "APP banner",
          id: 1,
        },
        {
          value: "小程序 banner",
          id: 2,
        }
      ],
      imageUrl: '',
      picturePath: '',
      imageUri: '',
      currenindex: 1,
      fromDate: {
        companyId: '',
        company: '',
        picturePath: '',
        pictureUrl: '',
        enable: 1,
        remark: '',
      },
      companylist: [],
      selectKeys: [],
      bgColor: '',
      colorId: '',
      ButtonList: [],
      tableParam: {
        companyId: '',
        companyName: '',
        enable: '',
        type: '',
        page: 1,
        pageSize: 10,
      }
    };
  },
  async created() {
    this.ButtonList = this.$ButtonList()
    this.UserInfo = await getUserInfo();
    getcompany({ typeId: "19da56b9e85648059e3cf1e7da497da4" }).then((res) => {
      this.companylist = res.data;
    });
    if (this.UserInfo.adminStatus !== 1) {
      this.tableParam.companyId = this.UserInfo.companyId;
      this.tableParam.companyName = this.UserInfo.companyName;
      this.tableParam.enable = 1;
      this.fromDate.companyId = this.UserInfo.companyId;
      this.fromDate.company = this.UserInfo.companyName;
    }
    this.tableParam.type = this.currenindex;
    this.gettableData();
    this.imageUri = process.env.VUE_APP_API_FILe;
    this.initColor();
  },
  watch: {
    currenindex: {
      //data所有属性都进行监听器，可使用字符串的形式监听对象属性（'item.item1'）
      handler() {
        this.tableParam.type = this.currenindex;
        this.tableParam.page = 1;
        this.init();
        this.initColor();
      },
      deep: false,
      immediate: false,
    },
  },
  methods: {
    initColor() {
      getBgColor({ type: this.currenindex }).then(res => {
        if (res.code === 1001) {
          this.bgColor = res.data.colorEncoding;
          this.colorId = res.data.id;
        }
      })
    },
    changeColor(value) {
      const params = {
        colorEncoding: value,
        id: this.colorId,
      }
      upDataBgColor(params).then(res => {
        if (res.code === 1001) {
          this.$message.success('修改成功');
        }
      })
    },
    UpdateData(type) {
      const id = this.selectKeys.map((item) => item.id)
      const params = {
        enable: type,
        id: id.join(','),
      }
      updateMany(params).then(res => {
        if (res.code === 1001) {
          this.$message.success('操作成功')
          this.gettableData();
        }
      })
    },
    handleEdit(data) {
      this.addDialog = true;
      this.addDialogTitle = '修改';
      this.picturePath = data.picturePath;
      this.imageUrl = process.env.VUE_APP_API_FILe + data.picturePath;
      this.fromDate = {
        companyId: data.companyId,
        company: data.companyName,
        picturePath: data.picturePath,
        pictureUrl: data.pictureUrl,
        id: data.id,
        enable: data.enable,
        remark: data.remark,
      }
    },
    addData() {
      this.addDialog = true;
      this.addDialogTitle = '添加';
      this.picturePath = '';
      this.imageUrl = '';
      this.fromDate = {
        companyId: this.UserInfo.companyId,
        company: this.UserInfo.companyName,
        picturePath: '',
        pictureUrl: '',
        enable: 1,
        remark: '',
      }
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      if (res.code === 1001) {
        this.picturePath = res.data.fileUrl;
      }
    },
    handleSelectionChange(selectKeys) {
      this.selectKeys = selectKeys;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传的图片格式不正确');
      }
      if (!isLt2M) {
        this.$message.error('上传的图片大小不能超过2M');
      }
      return isJPG && isLt2M;
    },
    init() {
      /*重置数据*/
      this.tableParam.page = 1;
      this.tableParam.enable = 1;
      this.gettableData();
    },
    choose(num) {
      this.currenindex = num;
    },
    pagessubmitFromDate() {
      if (!this.picturePath) {
        this.$message.warning('请上传图片')
        return
      }
      const slef = this;
      this.$refs.dialogForm.validate((valid) => {
        const params = {
          ...slef.fromDate,
          type: slef.currenindex,
          picturePath: this.picturePath,
        }
        if (valid) {
          if (params.id) {
            updateOne(params).then((res) => {
              if (res.code === 1001) {
                slef.resefrom();
                slef.gettableData();
                slef.$message.success('修改成功');
              }
            });
            return
          }
          saveOne(params).then((res) => {
            if (res.code === 1001) {
              slef.resefrom();
              slef.gettableData();
              slef.$message.success('新增成功');
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resefrom() {
      this.addDialog = false;
      this.$refs.dialogForm.resetFields();
    },
  },
};
</script>
<style lang="scss">
.mobilebanner {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
<style lang="scss" scoped>
.dialoginfo {
  padding: 0 20px 0 20px;
  .el-input,
  .el-select {
    width: 320px;
  }
}
.dialoginfo-title {
  display: flex;
  align-items: center;
  height: 50px;
  > div {
    width: 4px;
    height: 20px;
    background: $bg_color;
  }
  > span {
    padding-left: 10px;
    font-size: 20px;
    color: $bg_color;
    font-weight: bold;
  }
}
.tabtop {
  width: 380px;
}
</style>
